package com.lsf.dunlian.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lsf.dunlian.Myappliction;
import com.lsf.dunlian.R;
import com.lsf.dunlian.adapter.BaseFragmentPagerAdapter;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.fragment.HomePageFragment;
import com.lsf.dunlian.fragment.MyPageFragment;
import com.lsf.dunlian.fragment.WorkPageFragment;
import com.lsf.dunlian.utils.audio.UpdateApk;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AMapLocationListener {
    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    private ViewPager viewPager;
    private LinearLayout HomePageBtn;
    private LinearLayout workPageBtn;
    private LinearLayout CourseBtn;
    private LinearLayout MyBtn;
    private ImageView homepageImg;
    private ImageView workpageImg;
    private ImageView myImg;
    private TextView homepageTv;
    private TextView workpageTv;
    private TextView myTv;
    public AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseUtils.setStatusBar(this);
        setContentView(R.layout.activity_main);
        Myappliction.mainActivity = this;
        String userId = PreferenceUtil.getSharedPreference(Constant.USERID);
        if (StringUtils.isEmpty(userId)){
            startActivity(new Intent(this,LoginActivity.class));
            finish();
        }
        Request();
        initView();
        updateApk();
    }

    private void initView() {
        HomePageBtn=findViewById(R.id.HomePageBtn);
        workPageBtn=findViewById(R.id.workPageBtn);
        CourseBtn=findViewById(R.id.CourseBtn);
        MyBtn=findViewById(R.id.MyBtn);
        viewPager=findViewById(R.id.viewPager);

        homepageImg=findViewById(R.id.homepageImg);
        workpageImg=findViewById(R.id.workpageImg);
        myImg=findViewById(R.id.myImg);
        homepageTv=findViewById(R.id.homepageTv);
        workpageTv=findViewById(R.id.workpageTv);
        myTv=findViewById(R.id.myTv);
        fragmentList.add(new HomePageFragment());
        fragmentList.add(new WorkPageFragment());
        fragmentList.add(new MyPageFragment());
        BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adapter);
        HomePageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(0);
                homepageImg.setBackgroundResource(R.drawable.sy_red);
                homepageTv.setTextColor(getResources().getColor(R.color.zhuti));
                myImg.setBackgroundResource(R.drawable.wd_gray);
                myTv.setTextColor(getResources().getColor(R.color.black));

                workpageImg.setBackgroundResource(R.drawable.gongzuo_huise);
                workpageTv.setTextColor(getResources().getColor(R.color.black));
            }
        });
        workPageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(1);
                homepageImg.setBackgroundResource(R.drawable.sy_gray);
                homepageTv.setTextColor(getResources().getColor(R.color.black));

                myImg.setBackgroundResource(R.drawable.wd_gray);
                myTv.setTextColor(getResources().getColor(R.color.black));

                workpageImg.setBackgroundResource(R.drawable.gongzuo_red);
                workpageTv.setTextColor(getResources().getColor(R.color.zhuti));
            }
        });
        MyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(2);
                homepageImg.setBackgroundResource(R.drawable.sy_gray);
                homepageTv.setTextColor(getResources().getColor(R.color.black));

                myImg.setBackgroundResource(R.drawable.wd_red);
                myTv.setTextColor(getResources().getColor(R.color.zhuti));

                workpageImg.setBackgroundResource(R.drawable.gongzuo_huise);
                workpageTv.setTextColor(getResources().getColor(R.color.black));
            }
        });

    }

    private void location() {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(MainActivity.this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        mLocationOption.setInterval(60000);
        mlocationClient.setLocationOption(mLocationOption);

        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
         mLocationOption.setOnceLocationLatest(true);
        mlocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                PreferenceUtil.putSharedPreference(Constant.CITY,amapLocation.getAddress());
                PreferenceUtil.putSharedPreference(Constant.CITYCODE,amapLocation.getCityCode());
            } else {
                if (amapLocation.getErrorCode() == 12) {
                    Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
                    Request();
                }
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
            }
        }
    }



    private void updateApk(){
        if (PreferenceUtil.getSharedPreference(Constant.USERID)==null)return;
        PermissionUtil.getInstance().request(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE,
//                        Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                        Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        new Thread(new UpdateApk(MainActivity.this)).start();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        new Thread(new UpdateApk(MainActivity.this)).start();
                    }
                    @Override
                    public void onPermissionDenied(String... permissions) {
                        Toast.makeText(MainActivity.this,"需要手动开启获取文件读写权限！"+permissions,Toast.LENGTH_SHORT).show();
                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                    }
                    @Override
                    public void onRationalShow(String... permissions) {
                        Toast.makeText(MainActivity.this,"需要手动开启获取文件读写权限！"+permissions,Toast.LENGTH_SHORT).show();
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                    }
                });
    }


    public void Request() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                location();
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    location();
                }
                break;
        }
    }

}